package dfl.bysj.service.impl;

import dfl.bysj.config.RedisKey;
import dfl.bysj.entity.Floor;
import dfl.bysj.mapper.FloorMapper;
import dfl.bysj.service.FloorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DFL
 * @since 2022-04-26
 */
@Service
public class FloorServiceImpl extends ServiceImpl<FloorMapper, Floor> implements FloorService {
    private RedisTemplate redisTemplate;


    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private List<Floor> floors;

    private AtomicReference<Floor> floorAtomicReference= new AtomicReference<>(new Floor());




    private void getFloors(){
        floors= (List<Floor>) redisTemplate.opsForValue().get(RedisKey.ALL_FLOOR);
        if (floors==null){
            updateRedisOfFloors();

        }
    }

    private void updateRedisOfFloors(){
        floors=list();
        redisTemplate.opsForValue().set(RedisKey.ALL_FLOOR,floors,7, TimeUnit.DAYS);
    }

    @Override
    public List<Floor> getAllFloors() {
        getFloors();
        return floors;
    }

    @Override
    public Floor getFloorByfloId(Integer floId) {
        getFloors();
        floors.stream()
                .filter(s->s.getFloId().equals(floId))
                .forEach(s->floorAtomicReference.set(s));
        if (floorAtomicReference.get().getFloId()==null){
            return null;
        }
        return floorAtomicReference.get();
    }
}
